package com.summer.data.connection;

import com.summer.data.Jsql;
import com.summer.data.dialect.Dialect;
import com.summer.data.exception.BaseException;
import com.summer.data.parameter.ParameterStruct;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

/**
 * 工具类
 * 
 * @author ydfqy
 */

public class Utils {

    public static void closeResulet(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException(e);
            }
        }
    }

    public static void closeStatement(Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException(e);
            }
        }
    }

    public static void closePreparedStatement(PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException(e);
            }
        }
    }

    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException(e);
            }
        }
    }

    public static void prepare(PreparedStatement ps, Dialect dialect, Jsql jsql) {
        List<ParameterStruct> parameterStructList = jsql.parameterStructList;
        if (!parameterStructList.isEmpty()) {

            for (int i = 0; i < parameterStructList.size(); i++) {

                ParameterStruct parameterStruct = parameterStructList.get(i);
                dialect.prepare(ps, i + 1, parameterStruct);

            }

        }
    }

    // public static void useConnectNoReturn(DataSource dataSource,
    // WithConnectReturnVoid fun) {
    // Connection conn = null;
    // try {
    // conn = dataSource.getConnection();
    // fun.apply(conn);
    // } catch (SQLException e) {
    // e.printStackTrace();
    // throw new SummerException(e);
    // } finally {
    // closeConnection(conn);
    // }
    // }

}
